package com.ruoyi.elasticsearch.service.impl;

import com.ruoyi.elasticsearch.common.SystemDefinition;
import com.ruoyi.elasticsearch.es.domain.DeviceDTO;
import com.ruoyi.elasticsearch.es.service.DeviceEsService;
import com.ruoyi.elasticsearch.service.IDeviceService;
import com.ruoyi.elasticsearch.vo.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class DeviceServiceImpl implements IDeviceService {

    @Autowired
    private DeviceEsService deviceEsService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean setStatus(String deviceId, Boolean status) {
        DeviceDTO deviceDTO = findDevice(deviceId);
        if( deviceDTO==null ) return false;
        boolean b = deviceEsService.updateStatus(deviceId, status);
        deviceDTO.setStatus(status);
        refreshDevice(deviceDTO);
        return b;
    }

    @Override
    public boolean updateTags(String deviceId, String tags) {
        DeviceDTO deviceDTO = findDevice(deviceId);
        if( deviceDTO==null ) return false;
        return deviceEsService.updateDeviceTag(deviceId,tags);
    }

    @Override
    public boolean saveDeviceInfo(DeviceDTO deviceDTO) {
        //查询设备 ，判断开关状态 ，如果是关闭则不处理
        DeviceDTO device= findDevice(deviceDTO.getDeviceId());
        if( device!=null && !device.getStatus() ) return false;
        System.out.println(device);
        // 如果当前设备查不到，新增
        if(device==null){
            deviceEsService.addDevices( deviceDTO );
        }else{
            //如果可以查询到，更新告警信息
            deviceEsService.updateDevicesAlarm(deviceDTO);
        }
        return true;
    }

    /**
     * 根据设备id查询设备
     * @param deviceId
     * @return
     */
    private DeviceDTO findDevice(String deviceId){

        DeviceDTO  deviceDTO = (DeviceDTO)redisTemplate.boundHashOps(SystemDefinition.DEVICE_KEY).get(deviceId);
        if(deviceDTO==null){
            deviceDTO = deviceEsService.searchDeviceById(deviceId);
            refreshDevice(deviceDTO);
        }
        return deviceDTO;
    }


    /**
     * 刷新缓存
     * @param deviceDTO
     */
    private void refreshDevice(DeviceDTO deviceDTO ){
        if(deviceDTO==null) return;
        redisTemplate.boundHashOps(SystemDefinition.DEVICE_KEY).put(deviceDTO.getDeviceId(),deviceDTO);
    }

    @Override
    public Pager<DeviceDTO> queryPage(Long page, Long pageSize, String deviceId, String tags, Integer state) {
        return deviceEsService.searchDevice(page,pageSize,deviceId,tags,state);
    }

    @Override
    public void updateOnLine(String deviceId, boolean b) {

    }
}
